package com.ra.action;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.ra.dao.ProductDAO;
import com.ra.model.product.Product;

@Controller
public class ProductController {

	private static Logger log = Logger.getLogger(ProductController.class);
	private ProductDAO productDAO = null;

	/**
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/productList.html")
	public ModelAndView getProductList(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		log.debug("ProductController::getProductList:: start ");
		ModelAndView modelAndView = new ModelAndView("listProducts");
		try {
			log.debug("ProductController::getProductList:: logic ");
			List<Product> products = getProductDAO().getAllProducts();
			modelAndView.addObject("listProducts", products);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return modelAndView;
	}
	
	@RequestMapping("/addProduct.html")
	public ModelAndView addProduct(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		ModelAndView modelAndView = new ModelAndView(
				"product/createProduct");
			log.debug("ProductController::addProduct:: Start");
			Product p = new Product();
			p.setName("P1");
			log.debug("ProductController::addProduct:: End");
			// loading the lookup values
			modelAndView.addObject("product", p);
		
		return modelAndView;
	}


	@RequestMapping("/updateProduct.html")
	public ModelAndView addProduct(HttpServletRequest request,
			@ModelAttribute("product") Product product,
			HttpServletResponse response) throws ServletException, IOException {
		log.debug("ProductController::getProductList:: start ");
		ModelAndView modelAndView = new ModelAndView("listProducts");
		try {
			log.debug("ProductController::getProductList:: logic ");
			getProductDAO().createProduct(product.getCode(), product.getName(),
					product.getDescription());
			modelAndView = getProductList(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return modelAndView;
	}

	public void setProductDAO(ProductDAO productDAO) {
		this.productDAO = productDAO;
	}

	public ProductDAO getProductDAO() {
		return productDAO;
	}

}
